package com.daykw.xiaohongshu.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Configuration
public class Const {

	@Autowired
	private Environment environment;

	public static final String SESSION_USER = "sessionUser";
	public static int COMMENT_THREAD;
	public static int ARTICLE_THREAD;
	public static int PAGE_THREAD;

	public static int FIAL_400 = 400;
	public static int FIAL_500 = 500;
	public static int FIAL = 999;
	public static int SUC = 200;

	public static boolean isproxy = true;

	public static String MDB_IP = "49.4.70.26";
	public static String MDB_DB = "xhs";
	public static Integer MDB_PORT = 37158;
	public static String MDB_USER = "xhs";
	public static String MDB_PWD = "admin123";

	public static String XD_ORDER = "ZF20181260473u15OkA";

	public static String XD_SCERT = "2e541abf6e0d4b4d9ac4cc67ae5efeed";

	public static String ZK_NODES = "60.205.144.251:2181";

	public static int IP_COUNT = 3;

	@PostConstruct
	public void doStart() {

		Const.ARTICLE_THREAD = environment.getProperty("article_thread", Integer.class);
		Const.COMMENT_THREAD = environment.getProperty("comment_thread", Integer.class);
		Const.PAGE_THREAD = environment.getProperty("page_thread", Integer.class);
		Const.MDB_IP = environment.getProperty("mdb.ip", String.class);
		Const.MDB_PORT = environment.getProperty("mdb.port", Integer.class);
		Const.IP_COUNT = environment.getProperty("ip_count", Integer.class);
		Const.ZK_NODES = environment.getProperty("zk", String.class);
	}

	public static String getLocalHostIp() throws Exception {
		try {
			String ip = null;
			InetAddress candidateAddress = null;
			// 遍历所有的网络接口
			for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces
					.hasMoreElements();) {
				NetworkInterface iface = ifaces.nextElement();
				// 在所有的接口下再遍历IP
				for (Enumeration<InetAddress> inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
					InetAddress inetAddr = inetAddrs.nextElement();
					if (!inetAddr.isLoopbackAddress()) {// 排除loopback类型地址
						if (inetAddr.isSiteLocalAddress()) {
							// 如果是site-local地址，就是它了
							candidateAddress = inetAddr;
						} else if (candidateAddress == null) {
							// site-local类型的地址未被发现，先记录候选地址
							candidateAddress = inetAddr;
						}
					}
				}
			}
			// 如果没有发现 non-loopback地址.只能用最次选的方案
			if (candidateAddress == null) {
				candidateAddress = InetAddress.getLocalHost();
			}
			ip = candidateAddress.getHostAddress();

			return ip;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
